package com.jucStudy.common.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;

public class QrCodeUtils {
    /**
     * @param text 加密文本
     * @param width 宽度
     * @param height 高度
     * @param filePath 文件输出目录
     *这个是以文件的方式写入到本地磁盘
     * */
    public static void generateQRCodeImage(String text, int width, int height, String filePath)
            throws WriterException, IOException {

        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        Path path = FileSystems.getDefault().getPath(filePath);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    /*
     * @param condContent 加密文本
     * @param width 宽度
     * @param height 高度
     * @param outputStream 响应输出流
     *这个是以输出流的方式响应给浏览器
     * */
    public static void createCodeToOutputStream(String condContent, int with, int height, OutputStream outputStream){

        if (condContent==null||"".equals(condContent.trim())){
            return;
        }
        condContent=condContent.trim();

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

        try {
            BitMatrix encode = multiFormatWriter.encode(condContent, BarcodeFormat.QR_CODE,with,height);

            MatrixToImageWriter.writeToStream(encode,"PNG",outputStream);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    //这里是输出到文件测试
    public static void main(String[] args) {
        String path = "/Users/mac/Desktop/截图/1.png";
        try {
            generateQRCodeImage("hello", 500, 300, path);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
